<template>
    <div class="warehouse-in-appoint" @click="place.isShowLicense = false">
        <div class="place-fixed" v-show="place.isShow" @click.self="place.isShow = false">
            <div class="place-box">
                <div class="place-text">请选择车牌归属地</div>
                <div class="place-content">
                    <span :class="['place-item', place.index == index ? 'place-item-active' : '']"
                        v-for="(item, index) in place.list" :key="index" @click="changeActiveIdx(index)">{{ item }}</span>
                </div>
            </div>
        </div>
        <van-form @submit="onSubmit">
            <van-cell-group class="appoint-section font-size-26" inset>
                <van-field v-model="appintForm.data.spckmc" is-link name="spckmc" label="仓库" placeholder="请选择" readonly
                    required @click="openWarehousePicker" :rules="[{ required: true, message: '请选择仓库' }]" />
                <van-field v-model="appintForm.data.rcrq" is-link name="datetimePicker" label="进仓日期" placeholder="请选择"
                    readonly required @click="openDatePicker" :rules="[{ required: true, message: '请选择进仓日期' }]" />
                <div class="car-box">
                    <div class="car-text" @click="place.isShow = true">
                        <span>{{ place.text }}</span>
                    </div>
                    <van-field v-model="appintForm.data.dzzy6" placeholder="填写车牌号" label="车牌号" @input="inputCar" required
                        :rules="[{ required: true, message: '请填写车牌号' }, {
                            pattern: /^[\a-\z\A-\Z0-9\u4e00-\u9fe5\uff1b\;]+$/,
                            message: '多个车牌请用分号；隔开',
                            trigger: 'onBlur'
                        }]" />
                    <div v-show="place.isShowLicense" class="car-list">
                        <div class="car-item" v-for="(item, index) in place.carList" :key="index"
                            @click="selectLicense(item)">
                            <span class="license">{{ item.dzzy6 }}</span>
                            <span>{{ item.dzzy7 }}</span>
                        </div>
                    </div>
                </div>
                <van-field v-model="appintForm.data.dzzy7"
                    @input="appintForm.data.dzzy7 = appintForm.data.dzzy7.replace(' ', '')"
                    @blur="appintForm.data.dzzy7 = appintForm.data.dzzy7.replace(' ', '')" placeholder="填写司机姓名"
                    label="司机姓名" />
                <van-field v-model="appintForm.data.dzzy8" placeholder="填写联系电话" label="联系电话" type="tel" />
                <van-field v-model="appintForm.data.dzzy10" placeholder="填写身份证号" label="身份证号" />
                <van-field v-model="appintForm.data.szkhmc" placeholder="填写仓储费结算方" label="仓储费结算方" label-width="105px"
                    :rules="[{ required: false, message: '请填写仓储费结算方,以便分开对账' },
                    { pattern: /^((?![\\\\\/\\:\\*\\?\\<\\>\\|]).)*$/, message: szkhmcMsg }]">
                    <template #button>
                        <van-button size="mini" plain type="primary" @click="copy">复制公司</van-button>
                    </template>
                </van-field>
                <van-field v-model="appintForm.data.dzbz" placeholder="填写进仓备注" label="备注" />
            </van-cell-group>
            <div class="warehouse-in-appoint-top display-flex justify-between align-center">
                <div class="flex-item">
                    <!-- <span>共</span>
                    <span class="font-CE0C0C">3</span>
                    <span>个记录，</span>
                    <span class="font-CE0C0C">3000</span>
                    <span> 件，</span>
                    <span class="font-CE0C0C">30.600</span>
                    <span>吨</span> -->
                    <div class="title">
                        <span>进仓货物信息：</span>
                    </div>
                </div>
                <van-button color="#CE0C0C" class="btn" @click="handleAdd">添加货物</van-button>
            </div>
            <div class="warehouse-in-appoint-list">
                <div class="section font-size-26" v-for="(item, index) in appintForm.data.inp" :key="index">
                    <div class="title display-flex justify-between align-center">
                        <span>{{ item.spzs }}</span>
                        <div class="display-flex align-center" @click="handleEdit(index)">
                            <van-image :src="editIcon" color="#255FB6" class="edit-icon" />
                            <span class="font-255FB6">修改</span>
                        </div>
                    </div>
                    <div class="content">
                        <div class="item display-flex justify-between">
                            <div class="flex-item">
                                <span class="font-999999">纱支：</span>
                                <span>{{ item.wpggA }}</span>
                            </div>
                            <div class="flex-item">
                                <span class="font-999999">品牌：</span>
                                <span>{{ item.spcd }}</span>
                            </div>
                        </div>
                        <div class="item display-flex justify-between">
                            <div class="flex-item">
                                <span class="font-999999">单重：</span>
                                <span>{{ item.spjsl }}KG</span>
                            </div>
                            <div class="flex-item">
                                <span class="font-999999">件数：</span>
                                <span>{{ item.spjs }}</span>
                            </div>
                        </div>
                        <div class="item display-flex justify-between">
                            <div class="flex-item">
                                <span class="font-999999">重量：</span>
                                <span>{{ item.spsl }}吨</span>
                            </div>
                            <div class="flex-item">
                                <span class="font-999999">批号：</span>
                                <span>{{ item.spbh || '--' }}</span>
                            </div>
                        </div>
                        <div class="item display-flex justify-between">
                            <div class="flex-item">
                                <span class="font-999999">柜号：</span>
                                <span>{{ item.spgh || '--' }}</span>
                            </div>
                            <div display="pull-right display-flex align-center" @click="handleDelete(index)">
                                <van-image :src="deleteIcon" fit="contain" class="delete-icon" />
                                <span class="font-999999 ml-7">删除</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="warehouse-in-appoint-btn">
                <van-button color="#255FB6" block class="btn" native-type="submit">提交进仓</van-button>
            </div>
        </van-form>

        <!-- <van-popup v-model:show="warehouseInDateShow" position="bottom">
            <van-datetime-picker
                v-model="appintForm.data.rcrq"
                type="date"
                title="选择进仓日期"
                @confirm="warehouseInDateConfirm"
            />
        </van-popup> -->
        <van-action-sheet v-model:show="warehouseData.showPicker" title="请选择仓库" class="pb-30">
            <div class="select-warehouse display-flex flex-wrap">
                <div v-for="(item, index) in warehouseData.columns" :key="item.spckid"
                    :class="item.active ? 'active item' : 'item'" @click="warehouseSelected(index)">
                    <span>{{ item.spckmc }}</span>
                </div>
            </div>
        </van-action-sheet>
        <van-calendar v-model:show="warehouseInDateShow" color="#255FB6" :min-date="new Date(2018, 0, 1)"
            @confirm="warehouseInDateConfirm" />
    </div>
</template>
<script setup lang="ts">
import { onMounted, reactive, ref, nextTick } from 'vue'
import type { Ref } from 'vue'
import { getWarehouse, getWarehouseInSelectPosition, storageCategoryCarInfoList } from '@/api/warehouse'
import { setWarehouseIn } from '@/api/warehouseIn'
import { formatDate } from '@/utils/util'
import deleteIcon from '@/assets/images/delete.png'
import editIcon from '@/assets/images/edit.png'
import { useRoute, useRouter } from 'vue-router'
import { msgError, msgSuccess, msgConfirm } from '@/utils/message'
import { setLocalStorage, getLocalStorage } from '@/utils/localStorage'
import type { WarehouseData, AppintForm, PositionData } from '@/type/warehouseIn'

const route = useRoute()
const router = useRouter()
const userInfo: any = getLocalStorage('userInfo')
const szkhmcMsg = '不能输入 \ / : * ? " < > | 等字符';
const warehouseData: any = reactive({
    showPicker: false,
    loading: false,
    query: {
        khmcid: '',
        spckmc: ''
    },
    params: {
        pageNum: 1,
        pageSize: 999
    },
    list: [],
    columns: [],
    total: 0
})
const positionData: PositionData = reactive({
    query: {
        spckid: '',
    }
})
const warehouseInDateShow: Ref<boolean> = ref(false)
const appintForm: AppintForm = reactive({
    data: {
        dzbz: '',
        dzid: 0,
        dzzy10: '',
        dzzy6: '',
        dzzy7: '',
        dzzy8: '',
        iszxf: '',
        iszyl: '',
        khlx: '商城',
        khmc: userInfo.shopName,
        khmcid: userInfo.shopId,
        spckid: '',
        spckmc: '',
        szkhmc: '',
        wbdh: '',
        spcwid: '',
        rcrq: formatDate(new Date()),
        inp: []
    }
})
let place: any = reactive({
    list: ['粤', '浙', '冀', '闽', '京', '津', '沪',
        '渝', '豫', '云', '辽', '黑', '湘', '皖',
        '鲁', '新', '苏', '赣', '鄂', '桂', '甘',
        '晋', '蒙', '陕', '吉', '贵', '贵', '藏',
        '川', '宁', '琼'
    ],
    text: '粤',
    index: 0,
    isShow: false,
    isShowLicense: false,
    carAllList: [],
    carList: []
})
onMounted(() => {
    getStorage()
    warehouse()
    getCarList()
})

function getStorage() {
    const data = getLocalStorage('warehouseIn')
    if (data) {
        appintForm.data = reactive(data)
    }
}
function inputCar(e: any) {
    let value = e.target.value;
    value = value.replaceAll(' ', '');
    value = value.replace(/[\u4e00-\u9fa5]/ig, '');
    nextTick(() => {
        appintForm.data.dzzy6 = value;
    })
    if (value) {
        place.carList = place.carAllList.filter((item: any) => {
            return item.dzzy6.indexOf(value) >= 0;
        })
        if (place.carList.length) {
            place.isShowLicense = true;
        } else {
            place.isShowLicense = false;
        }
    } else {
        place.carList = [];
        place.isShowLicense = false;
    }
}
function selectLicense(item: any) {
    place.isShowLicense = false;
    let license = item.dzzy6;
    if (checkChinese(license)) {
        place.text = license.slice(0, 1);
        license = license.slice(1);
        place.list.map((text: string, index: number) => {
            if (text == place.text) {
                place.index = index;
                return;
            }
        })
    }
    nextTick(() => {
        appintForm.data.dzzy6 = license;
        appintForm.data.dzzy7 = item.dzzy7;
        appintForm.data.dzzy8 = item.dzzy8;
        appintForm.data.dzzy10 = item.dzzy10;
    })
}

function changeActiveIdx(index: number) {
    place.index = index;
    place.text = place.list[index]
    place.isShow = false;
}
function getCarList() {
    storageCategoryCarInfoList({ shopid: userInfo.shopId }).then((res: any) => {
        place.carAllList = res.data || [];
        place.carList = res.data || [];
        place.text = getLocalStorage('warehouseInCarText') || '粤';
    })
}

function checkChinese(str: string) {
    var reg = new RegExp("[\\u4E00-\\u9FFF]+", "g");
    return reg.test(str);
}
function warehouse() {
    warehouseData.loading = true
    getWarehouse(warehouseData.query, warehouseData.params).then((res: any) => {
        const data = res.rows
        warehouseData.list = data
        warehouseData.columns = data.map((a: any) => {
            return {
                spckid: a.spckid, spckmc: a.spckmc, active: false
            }
        })
        warehouseData.loading = false
    })
}

function warehouseInSelectPosition() {
    getWarehouseInSelectPosition(positionData.query).then((res: any) => {
        appintForm.data.spcwid = res.data[0].liid
    })
}

function warehouseInSubmit() {
    const inp = appintForm.data.inp
    for (let i in inp) {
        inp[i].ssrqid = appintForm.data.rcrq
        inp[i].spcwid = appintForm.data.spcwid
    }
    let form = JSON.parse(JSON.stringify(appintForm.data))
    form.dzzy6 = place.text + form.dzzy6
    setWarehouseIn(form).then(res => {
        msgSuccess('提交成功')
        router.push({ path: '/warehouseIn' })
    })
}

function onSubmit() {
    const form = JSON.parse(JSON.stringify(appintForm.data));
    if ((form.khmc == '厦门国贸集团股份有限公司' || form.khmc == '厦门国贸纺原有限公司' || form.khmc == '国贸启润(杭州)有限公司') && form.szkhmc == '') return msgError('仓储费结算方不能为空！');
    const inp = appintForm.data.inp
    if (inp && inp.length == 0) return msgError('请添加货物')
    msgConfirm('是否确认提交？').then((res: any) => {
        warehouseInSubmit()
    })
}

function openWarehousePicker() {
    warehouseData.showPicker = !warehouseData.showPicker
}

function warehouseSelected(index: number) {
    if (warehouseData.list[index].isIn === false) return msgError('当前仓库容量紧张，仅供包仓客户存放，请选择其他仓库')
    appintForm.data.spckmc = warehouseData.list[index].spckmc
    const spckid: string = warehouseData.list[index].spckid
    appintForm.data.spckid = spckid
    positionData.query.spckid = spckid
    warehouseInSelectPosition()
    openWarehousePicker()
}

function openDatePicker() {
    warehouseInDateShow.value = !warehouseInDateShow.value
}

function warehouseInDateConfirm(value: string) {
    appintForm.data.rcrq = formatDate(value)
    openDatePicker()
}

function handleEdit(index: number) {
    router.push({ path: '/warehouseIn/edit', query: { editIndex: index } })
}

function handleDelete(index: number) {
    msgConfirm('是否确认删除货物？').then((res: any) => {
        let data = getLocalStorage('warehouseIn')
        data.inp.splice(index, 1)
        setLocalStorage('warehouseIn', data)
        appintForm.data = data
    })

}

function copy() {
    appintForm.data.szkhmc = appintForm.data.khmc
}

function handleAdd() {
    setLocalStorage('warehouseIn', appintForm.data)
    setLocalStorage('warehouseInCarText', place.text)
    router.push({ path: '/warehouseIn/add' })
}
</script>
<style lang="scss" scoped>
.warehouse-in-appoint {
    padding-bottom: 150px;

    .appoint-section {
        margin-top: 36px;
        border-radius: 10px;
    }

    &-top {
        padding: 36px;
        font-size: 26px;

        .title {
            border-left: 8px solid #CE0C0C;
            padding-left: 26px;
        }

        .btn {
            height: 60px;
            border-radius: 8px;
        }
    }

    &-list {
        padding: 0 36px;

        .section {
            border-radius: 10px;
            background-color: #fff;
            padding: 26px;
            margin-bottom: 20px;

            .title {
                padding-left: 18px;
                margin-bottom: 26px;

                .edit-icon {
                    width: 30px;
                    height: 29px;
                    margin-right: 9px;
                }
            }

            .content {
                border-top: 1px solid #EEEEEE;
                padding: 26px 0 0;

                .item {
                    padding-bottom: 10px;
                }

                .delete-icon {
                    width: 25px;
                    height: 28px;
                }
            }
        }
    }

    &-btn {
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        padding: 20px 36px;

        .btn {
            border-radius: 10px;
        }
    }

    .select-warehouse {
        padding: 15px 20px 30px;
        max-height: 550px;
        font-size: 26px;

        .item {
            min-width: 150px;
            padding: 0 20px;
            display: inline-block;
            height: 60px;
            line-height: 60px;
            color: #999;
            text-align: center;
            border-radius: 30px;
            border: 1px solid #999;
            margin: 15px;

            &.active {
                color: #fff;
                border: 1px solid #255FB6;
                background: #255FB6;
            }
        }
    }

    .place-fixed {
        position: fixed;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        background: rgba(0, 0, 0, 0.4);
        z-index: 9999;

        .place-box {
            box-sizing: border-box;
            padding: 30px;
            position: absolute;
            left: 0;
            right: 0;
            bottom: 0;
            width: 100%;
            height: 620px;
            font-size: 32px;
            background: #FFFFFF;
            border-radius: 16px 16px 0px 0px;

            .place-text {
                margin-bottom: 30px;
                font-family: PingFangSC-Semibold, PingFang SC;
                font-weight: 600;
                color: #333333;
            }

            .place-content {
                display: flex;
                flex-wrap: wrap;

                .place-item {
                    margin-right: 20px;
                    margin-bottom: 22px;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    width: 80px;
                    height: 80px;
                    background: #F5F5F5;
                    border-radius: 8px;

                    &:nth-child(7n) {
                        margin-right: 0px !important;
                    }
                }

                .place-item-active {
                    background: #108EE9;
                    color: #FFFFFF;
                }

            }

        }
    }

    .car-box {
        position: relative;

        .car-text {
            box-sizing: border-box;
            position: absolute;
            z-index: 1;
            left: 150px;
            top: 10px;
            display: flex;
            align-items: center;
            width: 66px;
            height: 60px;
            background: #E3EFFC;
            border-radius: 4px;
            border: 2px solid #D6E9FC;
            font-size: 30px;
            font-weight: 400;
            color: #333333;

            span {
                margin-left: 5px;
            }

            &::after {
                position: absolute;
                right: 5px;
                top: 50%;
                transform: translateY(-50%);
                content: '';
                width: 0;
                height: 0;
                border-top: 10px solid #333;
                border-right: 10px solid transparent;
                border-left: 10px solid transparent;
            }
        }

        .car-list {
            padding: 0 30px;
            position: absolute;
            left: 0;
            right: 0;
            z-index: 99;
            top: 90px;
            max-height: 352px;
            background: #FFFFFF;
            box-shadow: 2px 8px 8px 8px rgb(29 35 41 / 5%) !important;
            font-size: 30px;
            overflow-y: auto;

            &::-webkit-scrollbar {
                display: none;
            }

            .car-item {
                z-index: 100;
                box-sizing: border-box;
                width: 100%;
                height: 88px;
                line-height: 88px;
                border-bottom: 1px solid #F6F6F6;

                .license {
                    display: inline-block;
                    margin-right: 50px;
                }
            }
        }
    }
}
</style>